package com.couldtest.Filter;

import com.couldtest.utils.FilterUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.sun.codemodel.internal.writer.FilterCodeWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import java.util.UUID;

//@Component
public class TrackingFilter  extends ZuulFilter {

    private static final Logger log = LoggerFactory.getLogger(ZuulFilter.class);
    /**过滤器排序
     * */
    private static final int FILTER_ORDER = 1;
    /**是否拦截
     * */
    private static final Boolean SHOULD_FILTER = true;

    @Autowired
    private FilterUtils filterUtils;



    /** 过滤器类型 前置，后置，路由过滤器
     * */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return SHOULD_FILTER;
    }

    /**校验请求头中是否包含链路请求id
     * */
    private  boolean isCorrelationIdPresent(){
        if(filterUtils.getCorrelationId() != null){
            return true;
        }
        return false;
    }

    /**生成一个uuid
     * */
    private String generateCorrelationId(){
        return UUID.randomUUID().toString();
    }

    @Override
    public Object run() {
        if(isCorrelationIdPresent()){
            log.debug("存在 tmx-correlation-ID{}",filterUtils.getCorrelationId());
        }
        else {
            filterUtils.setCorrelationId(generateCorrelationId());
            log.debug("生成 tmx-correlation-ID{}",filterUtils.getCorrelationId());
        }
        RequestContext ctx = RequestContext.getCurrentContext();
        log.debug("当前请求路径，{}",ctx.getRequest().getRequestURI());
        log.debug("当前请求路径，{}",ctx.getRequest().getRequestURL());
        return null;
    }



}
